package uba.ing2.subite.services.authorizationrules;

import java.util.Arrays;
import java.util.Collection;

import uba.ing2.subite.domain.Invoice;
import uba.ing2.subite.domain.PaymentCard;
import uba.ing2.subite.services.PaymentAuthorizationResult;

/**
 * Composición de reglas de autorización, esta regla retorna <i>autorizado</i> cuando
 * todas sus reglas "hijas" retornan <i>autorizado</i>.
 */
public class CompositePaymentAuthorizationRule implements PaymentAuthorizationRule {
    private Collection<PaymentAuthorizationRule> rules;

    /**
     * Factory method que facilita la creación de reglas compuestas.
     * @param rules reglas a componer
     * @return una regla compuesta de las reglas dadas
     */
    public static CompositePaymentAuthorizationRule withAll(PaymentAuthorizationRule... rules) {
    	return new CompositePaymentAuthorizationRule(Arrays.asList(rules));
    }

	public CompositePaymentAuthorizationRule(Collection<PaymentAuthorizationRule> rules) {
    	this.rules = rules;
    }

	@Override
	public PaymentAuthorizationResult apply(Invoice invoice, PaymentCard card) {
    	for (PaymentAuthorizationRule rule : rules) {
    		PaymentAuthorizationResult result = rule.apply(invoice, card);
    		if (!result.isAuthorized()) return result;
    	}
        return PaymentAuthorizationResult.autorized();
	}
}
